<template>
  <div>
    <div>
      <el-form :inline="true" :model="user" class="demo-form-inline">

        <el-form-item label="培训计划">
          <el-select v-model="user.trainingPlanId" placeholder="请选择">
            <el-option
                v-for="item in trainingPlanList"
                :key="item.value"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="姓名">
          <el-input v-model="user.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="所属机构">
          <el-select v-model="user.agencyId" placeholder="请选择">
            <el-option
                v-for="item in agencyList"
                :key="item.value"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="show">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="clear">清空</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportData">导出</el-button>
        </el-form-item>

      </el-form>


      <div>
        <h1 v-show="tableData.length===0" style="margin-top: 200px">请先选择培训计划</h1>
        <div v-show="tableData.length!==0">
          <el-descriptions title="学习情况统计分析" direction="vertical" :column="4" border>
            <el-descriptions-item label="总体学习完成度">{{ rateOfLearning }}</el-descriptions-item>
            <el-descriptions-item label="完成/总人数">{{ completedNum }}/{{ uncompletedNum }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <el-table
            v-show="tableData.length!==0"
            id="tableId"
            max-height="500"
            v-loading="loading"
            highlight-current-row
            ref="multipleTable"
            tooltip-effect="dark"
            border
            :data="tableData"
            style="margin: 0 auto; width: 100%;"
        >
          <el-table-column prop="id" label="编号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" header-align="center" align="center"></el-table-column>
          <el-table-column prop="agencyId" label="归属机构" header-align="center" align="center">
            <template slot-scope="scope">
              {{ getAgencyName(scope.row.agencyId) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="400" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="updateInfo(scope.row.id)"
              >查看学习情况
              </el-button>

            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-dialog :visible.sync="dialogVisible" :before-close="close">

        <el-table
            max-height="500"
            highlight-current-row
            ref="multipleTable"
            tooltip-effect="dark"
            border
            :data="userSituation"
            style="margin: 0 auto; width: 100%;"
        >
          <el-table-column prop="documentVideoId" label="视频文档编号" header-align="center"
                           align="center"></el-table-column>
          <el-table-column prop="type" label="文档视频名" header-align="center" align="center">
            <template slot-scope="scope">
              {{ getDocumentVideoName(scope.row.documentVideoId) }}
            </template>
          </el-table-column>
          <el-table-column prop="percentage" label="完成进度" header-align="center" align="center">
            <template slot-scope="scope">
              {{ scope.row.percentage }}%
            </template>
          </el-table-column>

        </el-table>
      </el-dialog>

    </div>

    <br>
    <!--分页工具条-->
    <footer>
      <el-pagination
          style="position:absolute;bottom: 20px;margin-left: 40vh"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :background="background"
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount">
      </el-pagination>
    </footer>
  </div>


</template>
<script>


import {addUser, changeUser, deleteUser, getAllUsers} from "@/api/user";
import {getAgencyList} from "@/api/agency";
import {getTrainingPlanList} from "@/api/trainingPlan";
import {getLearningSituationList, getLearningSituationOfOnePlan} from "@/api/learningSituation";
import {getDocumentVideoList} from "@/api/documentVideo";
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 表格数据
      tableData: [],
      addOrUpdate: true,//true为add
      user: {},
      form: {},
      posts: [],
      multipleSelection: [],
      selectedIds: [],
      agencyList: [],
      formLabelWidth: "80px",
      theMajorOfMy: "",
      trainingPlanList: [],
      userSituation: [],
      documentVideoList: [],
      loading: false,
      //统计分析
      rateOfLearning: 0,
      completedNum: 0,
      uncompletedNum: 0,


    }
  },
  methods: {

    show() {
      this.rateOfLearning = 0;
      this.completedNum = 0;
      this.uncompletedNum = 0;
      getLearningSituationOfOnePlan(this.user, this.currentPage, this.pageSize).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;
          if (this.tableData.length === 0 && this.currentPage > 1) {
            this.currentPage -= 1;
            this.show()
          }

          //计算统计属性
          let totalAverage = 0;
          this.uncompletedNum = this.tableData.length;

          for (let i = 0; i < this.tableData.length; i++) {

            let totalPercentage = 0; // 用于累加所有percentage值
            let num = 0;
            for (let j = 0; j < this.tableData[i].learningSituation.length; j++) {

              // 累加percentage值
              totalPercentage += this.tableData[i].learningSituation[j].percentage;
              if (this.tableData[i].learningSituation[j].percentage === 100) {
                num += 1;
              }
              if (num === this.tableData[i].learningSituation.length) {
                this.completedNum += 1;
              }
            }
            if (this.tableData[i].learningSituation.length !== 0) {
              let averagePercentage = totalPercentage / this.tableData[i].learningSituation.length;
              totalAverage += averagePercentage;
              //console.log("averagePercentage", averagePercentage)
            }
          }
          this.rateOfLearning = totalAverage / this.tableData.length;


        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    clear() {
      this.user = {};
      this.tableData =[];
    },
    add() {
      this.user = {};
      this.user.password = "1234567";
      this.addOrUpdate = true;
      this.dialogVisible = true;
    },
    addForm() {

      if (this.addOrUpdate) {
        addUser(this.user).then(res => {
          if (res.data.code === 1) {
            this.$message.success("保存成功")
            this.dialogVisible = false;
            this.show();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
        });
      } else {
        changeUser(this.user).then(res => {
          console.log(res)
          if (res.data.code === 1) {
            this.$message.success("更新成功")
            this.dialogVisible = false;
            this.user.status = "正常";
            this.show();
          }
        }).catch(e => {
        });
      }

    },

    close() {
      this.dialogVisible = false;
      this.user = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateInfo(id) {
      this.addOrUpdate = false;
      this.userSituation = this.tableData.filter(data => data.id == id)[0].learningSituation;
      this.dialogVisible = true;
    },

    getAllAgencyList() {
      getAgencyList().then((res) => {
        if (res.data.code === 1) {
          this.agencyList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getAgencyName(id) {
      let agency = this.agencyList.find(data => data.id === id);
      return agency ? agency.name : "";
    },
    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.show();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.show();
    },

    getTrainingsPlanList() {
      getTrainingPlanList().then((res) => {
        if (res.data.code === 1) {
          this.trainingPlanList = res.data.data;
        } else {
          console.log(res.data.msg);
        }
      }).catch((e) => {
      })
    },

    getDocumentVideoName(id) {
      const types = this.documentVideoList.find(t => t.id === id);
      return types ? types.name : '';
    },
    getDocumentVideoLists() {
      getDocumentVideoList().then((res) => {
        if (res.data.code === 1) {
          this.documentVideoList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getTrainingPlanName(id){
      const types = this.trainingPlanList.find(t => t.id === id);
      return types ? types.name : '';
    },

    //导出
    async exportData() {

      this.loading = true;
      this.currentPage = 1;
      this.pageSize = this.totalCount;


      try {
        await getLearningSituationList(this.user).then((res) => {
          if(res.data.code===1){
            this.tableData=res.data.data;
            //将learningSituationList拆开放入属性中
            let dataList = [];
            for (let i = 0; i < this.tableData.length; i++) {
              let t = {
                id: this.tableData[i].id,
                name: this.tableData[i].name,
                agencyId: this.tableData[i].agencyId
              }
              if(this.tableData[i].learningSituation!==null){
                for (let j = 0; j < this.tableData[i].learningSituation.length; j++) {
                  let situation = this.tableData[i].learningSituation[j];
                  // 将 learningSituation 的属性添加到 rowData 中，通过添加前缀来避免属性名冲突
                  t[`documentVideoId_${situation.documentVideoId}_percentage`] = situation.percentage+'%'; // 例如：percentage_0, name_0 等
                }
              }
              dataList.push(t);
            }
            const data =dataList;

            // 创建工作簿对象
            const wb = XLSX.utils.book_new();

            // 将数据添加到工作簿中，假设 data 是一个二维数组或对象数组
            // 如果 data 是对象数组，使用 XLSX.utils.json_to_sheet(data)
            // 如果 data 是二维数组，使用 XLSX.utils.aoa_to_sheet(data)
            const ws = XLSX.utils.json_to_sheet(data);

            // 将工作表添加到工作簿中
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
            // 写入工作簿，生成 XLSX 文件
            const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
            // 使用 FileSaver 保存文件
            try {
              FileSaver.saveAs(
                  new Blob([wbout], {type: "application/octet-stream"}),
                  this.getTrainingPlanName(this.user.trainingPlanId)+"_学习进度.xlsx"
              );
            } catch (e) {
              console.error(e);
            }


          }
        }).catch((e) => {})
      } finally {
        this.currentPage = 1;
        this.pageSize = 5;
        this.show();
        this.loading = false;
      }
    },


  },
  mounted() {
    this.getAllAgencyList();
    this.getTrainingsPlanList();
    this.getDocumentVideoLists();
  },
};
</script>


<style>
* {
  margin: 0;
  padding: 0;
}

</style>


